<template>
  <el-dialog :title="isEdit ? '编辑兑换码' : '新增兑换码'" v-model="dialogVisible" width="600px" :close-on-click-modal="false" @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="exchange-code-form">
      <el-form-item label="兑换码数量" prop="count">
        <el-input-number v-model="form.count" :min="1" :max="20" placeholder="请输入兑换码数量" style="width: 100%" />
        <div class="form-tip">批量生成时，系统会自动生成指定数量的兑换码</div>
      </el-form-item>

      <el-form-item label="可兑换会员类型" prop="membershipType">
        <el-select v-model="form.membershipType" placeholder="请选择会员类型" style="width: 100%">
          <el-option label="月会员" value="vip_month" />
          <el-option label="季会员" value="vip_quarter" />
          <el-option label="年会员" value="vip_year" />
        </el-select>
      </el-form-item>

      <el-form-item label="兑换码前缀" prop="prefix">
        <el-input v-model="form.prefix" placeholder="请输入兑换码前缀（可选）" maxlength="10" show-word-limit />
        <div class="form-tip">前缀将添加到生成的兑换码前面，便于识别和管理</div>
      </el-form-item>

      <el-form-item label="有效期" prop="expireDays">
        <el-input-number v-model="form.expireDays" :min="1" :max="365" placeholder="请输入有效期天数" style="width: 100%" />
        <div class="form-tip">兑换码的有效期，从生成时间开始计算</div>
      </el-form-item>

      <el-form-item label="备注" prop="description">
        <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入备注信息（可选）" maxlength="200" show-word-limit />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          {{ isEdit ? '更新' : '生成兑换码' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
  import { ref, reactive, computed, watch, nextTick } from 'vue';
  import { ElMessage } from 'element-plus';
  import { createExchangeCode, updateExchangeCode } from '@/api/exchangeCode';

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false
    },
    exchangeCode: {
      type: Object,
      default: null
    }
  });

  const emit = defineEmits(['update:modelValue', 'success']);

  const dialogVisible = computed({
    get: () => props.modelValue,
    set: val => emit('update:modelValue', val)
  });

  const isEdit = computed(() => !!props.exchangeCode);

  const formRef = ref();
  const submitLoading = ref(false);

  const form = reactive({
    count: 1,
    membershipType: '',
    prefix: '',
    expireDays: 30,
    description: ''
  });

  const rules = {
    count: [
      { required: true, message: '请输入兑换码数量', trigger: 'blur' },
      { type: 'number', min: 1, max: 1000, message: '兑换码数量必须在1-1000之间', trigger: 'blur' }
    ],
    membershipType: [{ required: true, message: '请选择会员类型', trigger: 'change' }],
    expireDays: [
      { required: true, message: '请输入有效期天数', trigger: 'blur' },
      { type: 'number', min: 1, max: 365, message: '有效期天数必须在1-365之间', trigger: 'blur' }
    ]
  };

  // 监听编辑数据变化
  watch(
    () => props.exchangeCode,
    newVal => {
      if (newVal) {
        // 编辑模式，填充表单数据
        Object.assign(form, {
          count: 1, // 编辑时数量固定为1
          membershipType: newVal.membershipType || '',
          prefix: newVal.prefix || '',
          expireDays: newVal.expireDays || 30,
          description: newVal.description || ''
        });
      } else {
        // 新增模式，重置表单
        resetForm();
      }
    },
    { immediate: true }
  );

  const resetForm = () => {
    Object.assign(form, {
      count: 1,
      membershipType: '',
      prefix: '',
      expireDays: 30,
      description: ''
    });
    nextTick(() => {
      formRef.value?.clearValidate();
    });
  };

  const handleClose = () => {
    dialogVisible.value = false;
    resetForm();
  };

  const handleSubmit = async () => {
    try {
      await formRef.value.validate();
      submitLoading.value = true;

      const submitData = {
        count: form.count,
        membershipType: form.membershipType,
        prefix: form.prefix,
        expireDays: form.expireDays,
        description: form.description
      };

      let response;
      if (isEdit.value) {
        // 编辑模式
        response = await updateExchangeCode(props.exchangeCode._id, submitData);
      } else {
        // 新增模式
        response = await createExchangeCode(submitData);
      }

      if (response.code === 200) {
        ElMessage.success(isEdit.value ? '更新成功' : '兑换码生成成功');
        emit('success');
        handleClose();
      } else {
        ElMessage.error(response.msg || (isEdit.value ? '更新失败' : '生成失败'));
      }
    } catch (error) {
      console.error('提交失败:', error);
      ElMessage.error('操作失败，请重试');
    } finally {
      submitLoading.value = false;
    }
  };
</script>

<style scoped>
  .exchange-code-form {
    padding: 20px 0;
  }

  .form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
    line-height: 1.4;
  }

  .dialog-footer {
    text-align: right;
  }
</style>
